const router = require('express').Router()
const { email: emailv } = require('../config/schema')
const { service, user, pass } = require('../config')
const code = require('../tool/code')
const { wrap } = require('../tool')
const nodemailer = require('nodemailer')

function html(code) {
   return `<!DOCTYPE html><html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Flying Node</title><style>h1{margin-left:.5em}p{margin:8px;margin-left:1.5em}.code{margin:1em auto;text-align:center}code{font-size:20px;padding:6px;font-family:Consolas;border:1px solid #ccc}.tips{font-size:14px}</style></head><body><h1>欢迎注册FLYING NODE: CSDN</h1><p>这里是你的验证码，自发送后五分钟内有效。</p><p class="tips">! 重新发送验证码会使仍在有效期内的上一个验证码失效</p><p class="tips">如果不是本人操作，请无视</p><p class="code"><code>{{auth code}}</code></p></body></html>`
      .replace('{{auth code}}', code)
}

let transporter = nodemailer.createTransport({
   service,
   port: 465,
   secureConnection: true,
   auth: {
      user,
      pass,
   }
});
/** * 发送邮件 */
function sendEmail(to, subject, html) {
   return new Promise(e => {
      transporter.sendMail({
         from: 'Flying 节点',
         to,
         subject,
         html
      }, (error, info) => {
         if (error) {
            console.log(error);
            e()
         } else {
            console.log('邮件发送成功')
            e(info)
         }
      });
   })
}

router.post('/authcode', wrap(async (req, res) => {
   const { email } = req.body
   if (!email) {
      res.send({
         code: '316',
         msg: '缺少email'
      })
   }
   const { error } = emailv.validate({ email })
   if (error) throw error.message

   const _code = code.add(email)
   const info = await sendEmail(email, 'Flying Node', html(_code))
   if (info) {
      res.send({
         msg: '已发送验证码',
         code: 200
      })
   } else {
      throw '500'
   }
}))

module.exports = router